from datetime import datetime

from django.db import models
from django.contrib.auth import get_user_model
from goods.models import Goods
# Create your models here.

User = get_user_model()


class ShoppingCart(models.Model):
    """
    购物车
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    goods = models.ForeignKey(Goods, verbose_name="商品", on_delete=models.CASCADE)
    nums = models.IntegerField(default=0, verbose_name=u"购买数量")
    add_time = models.DateTimeField(default=datetime.now, verbose_name="添加时间")

    class Meta:
        verbose_name = '购物车'
        verbose_name_plural = verbose_name
        unique_together = ('user', 'goods')

    def __str__(self):
        return f'{self.goods.name} - {self.goods.goods_num}'


class OrderInfo(models.Model):
    """
    订单详情
    """
    ORDER_STATUS = (
        ("TRADE_SUCCESS", "成功"),
        ("TRADE_CLOSED", "超时关闭"),
        ("WAIT_BUYER_PAY", "交易创建"),
        ("TRADE_FINISHED", "交易结束"),
        ("paying", "待支付"),
    )
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="下单用户")
    order_sn = models.CharField(max_length=32,null=True, blank=True, unique=True, verbose_name="订单sn")
    trade_no = models.CharField(max_length=100, unique=True, null=True, blank=True, verbose_name="支付宝交易号")
    pay_status = models.CharField(max_length=30, verbose_name="支付状态", default="paying", choices=ORDER_STATUS)
    post_script = models.TextField(max_length=200, verbose_name="订单留言")
    order_mount = models.DecimalField(max_digits=10, default=0.0, decimal_places=2, verbose_name="订单金额")
    pay_time = models.DateTimeField(null=True, blank=True, verbose_name="支付时间")

    address = models.CharField(max_length=256, default="", verbose_name="收货地址")
    signer_name = models.CharField(max_length=32, default="", verbose_name="签收人")
    signer_mobile = models.CharField(max_length=11, default="", verbose_name="签收人电话")
    add_time = models.DateTimeField(auto_now_add=True, verbose_name="添加时间")

    class Meta:
        verbose_name = '订单'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.order_sn


class OrderGoods(models.Model):
    """
    订单的商品详情
    """
    order = models.ForeignKey(OrderInfo, on_delete=models.CASCADE, verbose_name="订单", related_name="goods")
    goods = models.ForeignKey(Goods, on_delete=models.CASCADE, verbose_name="商品")
    goods_num = models.IntegerField(default=1, verbose_name="商品数量")
    add_time = models.DateTimeField(default=datetime.now,
                                    verbose_name="添加时间")


    class Meta:
        verbose_name = '订单商品'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.order.order_sn
